package com.foreknow.service.impl;

import com.foreknow.dao.impl.BusinessDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.model.Business;
import com.foreknow.service.BusinessService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BusinessServiceImpl implements BusinessService {
    private DBManager db;
    private Connection conn = null;
    private BusinessDaoImpl bdao = new BusinessDaoImpl();

    /**
     * 表格
     * @return
     */
    @Override
    public List<Object> bTable() {
        Business business = new Business();
        db = DBManager.getInstance();
        conn=db.getConnection();
        bdao.setConnection(conn);
        List<Object> list = null;
        try {
            list =bdao.bQueryAll(business);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 添加
     * @param business
     * @return
     */
    @Override
    public boolean add(Business business) {
        db = DBManager.getInstance();
        conn=db.getConnection();
        bdao.setConnection(conn);
        try {
            boolean isRight = bdao.bSave(business);
            if (isRight){
                conn.commit();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 搜索
     * @param bName
     * @return
     */
    @Override
    public List<Object> query(String bName) {
        db = DBManager.getInstance();
        conn=db.getConnection();
        bdao.setConnection(conn);
        List<Object> list = new ArrayList<>();
        try {
          list = bdao.bQueryById(bName);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public boolean delete(int bid) {
        db = DBManager.getInstance();
        conn=db.getConnection();
        bdao.setConnection(conn);
        try {
            boolean isRight = bdao.bDelete(bid);
            if (isRight){
                conn.commit();
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public int update(Business business,int bid) {
        db = DBManager.getInstance();
        conn=db.getConnection();
        bdao.setConnection(conn);
        try {
            int b = bdao.bUpdate(business,bid);
           if (business.getBusinessId() == bid){
               return b;
           }
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }


}
